【问题标题】:template typedef C++11模板类型定义 C++11
【发布时间】:2014-08-30 13:31:38
【问题描述】:

我试图使用 C++11 的“使用 =”语法来定义模板化比较函数。然后我定义了一个模板函数,并希望将其分配给“ComparisonFunction”类型的 compareFunc。

  template<typename ValueType> using ComparisonFunction = bool (*)
                 (ValueType const & val1, ValueType const & val2);

    template<typename ValueType>
    bool equalFunction(ValueType const & val1, ValueType const & val2) {
        return val1==val2;
    }

    template<typename ValueType>
    ComparisonFunction<ValueType> comparisonFunc = equalFunction<ValueType>;   //Error is here

    int main()
    {

    }

前几行有效,但声明 equalFunc(甚至没有给它一个值)给出了错误

error: template declaration of 'bool (* equalFunc)(const ValueType&, const ValueType&)

我在此错误中发现的所有内容都与不存在“using =" 语法的 C++03 相关。

提前致谢

【问题讨论】:

  • 您询问类型定义,但您遇到的问题是函数定义或函数指针定义,而不是类型定义。

标签: templates c++11 typedef using


【解决方案1】:

你的声明

template<typename ValueType>
ComparisonFunction<ValueType> comparisonFunc = equalFunction<ValueType>;

是一个变量模板,因为声明是针对变量comparisonFunc,而不是类型或函数。 C++14 允许变量模板,但 C++11 中没有这样的东西。

【讨论】:

  • C++14 将允许变量模板... -> "Will"?
  • 哦,我错过了它已经被官方批准了!
  • 模板变量?!你能指出我的标准/草案吗?我可以想象静态 constexpr 模板变量,但正常非静态?
  • @firda 请参阅当前标准的第 14/1 段“模板 [temp]”:“由变量的模板声明引入的声明是 变量模板”。
【解决方案2】:

由于equalFunction 的每个实例化都需要不同的函数指针,因此可以将ComparisonFunction 设为仿函数。正如您所说,C++03 中不存在模板别名,因此您的最终代码是:

template<typename ValueType>
bool equalFunction(ValueType const & val1, ValueType const & val2) {
    return val1==val2;
}

template <typename ValueType>
struct ComparisonFunction
{
    bool operator()(ValueType const & val1, ValueType const & val2)
    {
        return equalFunction(val1, val2);
    }
};

【讨论】:

  • 我的目标是创建一个类型 ComparisonFunction 以便我可以分配任何类型的比较函数。例如,一开始它应该是一个equalFunction,后来在代码中,这个相同的变量应该引用一个LessThanFunction
猜你喜欢
  • 2011-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
相关资源
最近更新 更多