【问题标题】:Why do I have to specialize it?为什么我必须专攻它?
【发布时间】: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:他们是。

标签: c++ templates


【解决方案1】:

condition 这里是你程序的一个变量。

模板参数必须是常量表达式(或类型),因此变量不适合,因为编译器无法根据运行时信息选择正确的特化。

【讨论】:

    【解决方案2】:
    static auto check(bool condition, Left left, Right right)-> decltype(Result<condition,Left,Right>::value)
    

    什么???

    您不能在编译时使用运行时变量condition 参数化模板!?

    【讨论】:

    • 也许他的意思是typeof (condition)?错误...但这并不适用于任何地方,不是吗?
    • 不,Result的第一个参数是bool value!
    【解决方案3】:

    随便写(去掉check之后):

    cout << Ternary::check_(IntToType<false>,a,s);
    

    【讨论】:

    • 是的,但我希望根据第一个参数选择正确的 check_。
    • @There:您不能在 C++ 中在运行时确定函数的返回类型。
    • @There 什么都没有......(哎呀,真是个昵称!)这正是将要发生的事情:在 auto tResult = Ternary::check_(IntToType, a, s); tResult 将是“Right”类型,在您的示例 std::string 中,您可以通过 deltype(tResult) tOther = "surely a string" 轻松验证。正如其他海报所述,您不能将运行时变量(条件)用作类模板 ID。
    猜你喜欢
    • 2019-10-27
    • 2019-11-02
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2015-04-04
    • 2011-01-28
    • 2015-03-09
    • 1970-01-01
    相关资源
    最近更新 更多