是否可以设计一个包含模板参数默认值的类

Can one design a class containing default values for template parameters?

本文关键字:包含模 参数 默认值 一个 以设计 是否      更新时间:2023-10-16

可以为模板类提供默认值,如下所示:

template<class T = int>
class Foo 
{ /* ... some implementation details ... */ };

是否可以通过另一个类提供默认值"int"?我想设计一个对象"参数",其中包含特定模板类的一些默认值。这些默认值应从输入配置文件中读取。从语法的角度来看,它应该看起来像这样:

template<class T = Parameters::FooDefaultValue>
class Foo 
{ /* ... some implementation details ... */ };

但是,我不知道是否可以使用某些 typdef 或模板别名或任何其他方法。

你知道这样的事情是否可能吗?否则,您知道我的问题的另一种解决方案吗?

谢谢!

您不能将类型设置为值,但是您可以使用值模板参数,例如

template<typename T = int, int DefaultValue = Parameters::FooDefaultValue>
class Foo
{
    ...
};

这当然要求Parameters::FooDefaultValue是编译时常量或constexpr

这是不可能的。模板参数(无论是类型还是值)必须在编译时知道,因此无法在运行时从配置文件中读取它们。

看看

std::enable_if 或者如果你没有 C++11,则等效的 boost::enable_if。我在想这样的事情;这不会编译,但也许是一个粗略的轮廓?

template<class T>
typename std::enable_if<is_of_type<T,Parameters>::value, Parameters::FooDefaultValue>::type 
    foo1(T t) 
{
    std::cout << "foo1: floatn";
    return t;
}

注意:is_of_type::值是一个非标准的东西。

相关文章: