是否可以设计一个包含模板参数默认值的类
Can one design a class containing default values for template parameters?
可以为模板类提供默认值,如下所示:
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::值是一个非标准的东西。
相关文章:
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 通过零参数构造函数创建的 glm::mat4 应该包含哪些值?
- 将 C# 对象(包含静态对象成员)作为参数传递给 C++/CLI 程序
- C ++引用函数参数似乎包含原始对象的副本,而不是充当"real reference"
- 生成包含给定类型的 N 个参数的可变参数列表的最佳方法?
- 为什么我应该在scanf()-家族成员中包含一个长度修饰符作为参数?有什么好处?使用长度修改器进行扫描的作用
- 如何将枚举类作为类模板参数包含在内?
- C/C++ 包含点的宏参数(成员访问运算符)
- 包含可变参数包的第一个可转换类型的别名的结构
- C 函数调用包装器包含类成员功能作为模板参数
- 为什么我们可以创建一个模板类结构,其中包含许多与声明结构时指定的参数不同的参数
- 传递多个参数的功能,该函数将类包含到其他函数
- 可以使用默认参数复制包含 lambda 的 std::函数吗?
- 休息:当我尝试制作包含JSON参数的requst时发出问题
- 如何在成员函数中包含默认参数
- 是否可以设计一个包含模板参数默认值的类
- 将包含所有参数的成员函数传递给 std::function
- 为什么有必要在每个函数之前包含模板参数,即使我们在函数中没有使用 diduced 类型
- 包含模板参数包的函数模板的部分排序