三元运算符
为什么编译器不能专门化这个函数,有没有办法强制他这样做?
我收到的错误:
错误 1 错误 C2893:无法专门化函数模板 ''unknown-type' Ternary::check(bool,Left,Right)'
#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;
}
__Updated__
template<bool Condition,class Left, class Right>
static auto check(Left left, Right right)->
typename 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;
}
Why compiler cannot specialize this function and is there a way to force him to do so?
The error I'm getting:
Error 1 error C2893: Failed to specialize function template ''unknown-type' Ternary::check(bool,Left,Right)'
#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;
}
__Updated__
template<bool Condition,class Left, class Right>
static auto check(Left left, Right right)->
typename 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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 C++0x 还没有足够的经验,但从我所见:
decltype
需要一个表达式,但Result<...>::value
是一种类型。只需删除decltype
;condition
是一个变量,不能将其用作模板参数。更新:
Int2Type
也是一种类型。您想要传递一个值:Int2Type()
。I don't have enough experience with C++0x yet, but from what I see:
decltype
expects an expression, butResult<...>::value
is a type. Just remove thedecltype
;condition
is a variable, you can't use it as a template parameter.UPDATE: also
Int2Type<Condition>
is again a type. You want to pass a value:Int2Type<Condition>()
.