在现代C ++中,是否可以将字符串文字作为参数传递给C ++模板? [英] Is it possible in modern C++ to pass a string literal as a parameter to a C++ template?

查看:100
本文介绍了在现代C ++中,是否可以将字符串文字作为参数传递给C ++模板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在现代C ++(C ++ 17或更高版本)中是否可以将字符串文字作为参数传递给C ++模板?

Is it possible in "modern C++" (C++17 or greater) to pass a string literal as a parameter to a C++ template?

我意识到你可以用构造函数参数做到这一点;我只是认为将其作为模板参数比将其深埋在cpp文件中更为方便。我很好奇这是否是现代C ++的新功能。请参阅下面的伪代码以了解我要执行的操作:

I realize you could do this with constructor argument; I just thought it would be more convenient to have it as a template argument, rather than buried deep in the cpp file. I was curious if maybe this was a new feature of modern C++. See Pseudo code below of what I'm trying to do:

伪代码示例:

// Header File /////////////////////////
template<constexpr string Name>
class ModuleBase {
public:
    ModuleBase();
    string name;
};

class xyz : ModuleBase<"xyz"> {
public:
    xyz();
};

// Cpp File //////////////////////////
template<string_literal Name>
ModuleBase<Name>::ModuleBase() {
    name = Name;
}

xyz::xyz() : ModuleBase() {

}


推荐答案

是,在

问题是确定模板非类型参数的唯一性很困难。

The problem was that determining uniqueness of a template non-type argument was difficult.

< => 宇宙飞船的操作员比较。如果它是非用户提供的(并且仅基于非用户提供的< => ,则递归重复)(和其他一些要求;请参见p0732 ),该类型可以用作非类型模板参数。

c++20 adds in a <=> spaceship operator comparison. If it is non-user provided (and based only off non-user provided <=> in turn, repeat recursively) (and a few other requirements; see p0732), the type can be used as a non-type template argument.

可以从 constexpr 构造函数中的原始字符串 构造此类类型,包括使用演绎指南它们会自动调整大小。

Such types can be constructed from raw "strings" in constexpr constructors, including using c++17 deduction guides to make them auto-size themselves.

由于存储的数据大小可能是该类型的一部分,因此您需要将该类型作为 auto 键入的非类型参数或自动推断的类型。

As the size of the data stored is probably going to be part of the type, you'll want to take the type as an auto typed non-type parameter or otherwise auto-deduced type.

请注意,将模板的实现放在cpp文件中通常是个坏主意。但这是另一个问题。

Note that placing the implementation of your template in a cpp file is usually a bad idea. But that is another question.

这篇关于在现代C ++中,是否可以将字符串文字作为参数传递给C ++模板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆