I tried to write three types of meta-programming template to check a class object is able to convert to an int or not.
#include <iostream>
using namespace std;
template<typename T>
struct meta1
{
static char(&resolve(int))[2];
static char resolve(...);
enum { value = sizeof(resolve(T())) - 1 };
};
template<typename T>
struct meta2
{
struct result_yes { char _[2]; };
typedef char result_no;
static result_yes resolve(int);
static result_no resolve(...);
enum { value = sizeof(resolve(T())) - 1 };
};
template<typename T>
struct meta3
{
static constexpr bool resolve(int) { return true; }
static constexpr bool resolve(...) { return false; }
enum { value = resolve(T()) }; // error C2131: expression did not evaluate to a constant
};
#define CHECK(FUNC_NAME) \
cout << "Checking " #FUNC_NAME << endl; \
cout << FUNC_NAME<int>::value << endl; \
cout << FUNC_NAME<string>::value << endl; \
int main()
{
CHECK(meta1)
CHECK(meta2)
CHECK(meta3)
}
and an error occured when using constexpr, error C2131: expression did not evaluate to a constant How can I fix this, and why this happened?
Thank you.
sizeofis in unevaluated context (that's why you might omit definition).enum { value = resolve(T()) };is in evaluated context, andstring{}is unusable in constant expression until C++20 (and currently not yet supported).