【发布时间】:2010-10-01 19:08:04
【问题描述】:
我做错了什么?
#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;
}
我遇到了错误:
"Error 1 error C2893: 无法专门化函数模板''unknown-type' Ternary::check(bool,Left,Right)'"
为什么? 编辑
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)
【问题讨论】:
-
类型是编译时结构。如果编译时不知道参数,就不能使用类型。
-
@GMan 我已经尝试过使用 Result
::value 但它也不起作用,并且 sizeof 是编译时运算符。有没有办法解决这个问题? -
someexpression是什么?这也需要在编译时知道... -
@GMan (sizeof(1) == 1 ? true : false)
-
比较的结果是布尔值,不需要条件。
sizeof(1) == 1应该是一个很好的模板参数,也许你应该编辑你测试它的方式。@Tyler:他们是。