我做错了什么?
#include "stdafx.h"
#include <iostream>
#include <string>
using std::cout;
using std::string;
template<int v>
struct Int2Type
{
enum {value = v};
};
template<bool condition,class Left, class Right>
struct Result;
template<class Left, class Right>
struct Result<true,Left,Right>
{
typedef Left value;
};
template<class Left, class Right>
struct Result<false,Left,Right>
{
typedef Right value;
};
struct Ternary
{
template<class Left, class Right>
static Right check_(Int2Type<false>, Left left, Right right)
{
return right;
}
template<class Left, class Right>
static Left check_(Int2Type<true>, Left left, Right right)
{
return left;
}
template<class Left, class Right>
static auto check(bool condition, Left left, Right right)-> decltype(Result<condition,Left,Right>::value)
{
return check_(Int2Type<condition>,left,right);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
int a = 5;
string s = "Hello";
cout << Ternary::check(false,a,s);
return 0;
}
我收到错误:
“错误1错误C2893:无法专门化功能模板''未知类型'三元::检查(布尔,左,右)'”
为什么呢? 的修改
template<class Left, class Right>
static auto check(bool condition, Left left, Right right)->
decltype(Result<(sizeof(int) == 1),Left,Right>::value)
{
return check_(Int2Type<condition>,left,right);
}
补充道:
Result<(sizeof(int) == 1)
答案 0 :(得分:2)
condition
这是您程序的变量。
模板参数必须是常量表达式(或类型),因此变量不适合,因为编译器无法根据运行时信息选择正确的特殊化。
答案 1 :(得分:0)
static auto check(bool condition, Left left, Right right)-> decltype(Result<condition,Left,Right>::value)
什么???
您无法在编译时使用运行时变量condition
来参数化模板!?
答案 2 :(得分:0)
只需写(删除check
后):
cout << Ternary::check_(IntToType<false>,a,s);