Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;20字符串文本模板参数工作示例_C++_Templates_C++20 - Fatal编程技术网

C++ C++;20字符串文本模板参数工作示例

C++ C++;20字符串文本模板参数工作示例,c++,templates,c++20,C++,Templates,C++20,有人可以发布一个C++20特性字符串模板的最小可复制示例作为模板参数吗 此文件不编译: template<std::basic_fixed_string T> class Foo { static constexpr char const* Name = T; public: void hello() const; }; int main() { Foo<"Hello!"> foo; foo.hello(); } 模板 福班{ 静态co

有人可以发布一个C++20特性字符串模板的最小可复制示例作为模板参数吗

此文件不编译:

template<std::basic_fixed_string T>
class Foo {
    static constexpr char const* Name = T;
public:
    void hello() const;
};

int main() {
    Foo<"Hello!"> foo;
    foo.hello();
}
模板
福班{
静态constexpr char const*Name=T;
公众:
void hello()常量;
};
int main(){
富富,;
喂;
}
我已根据以下内容编写了一个有效的解决方案:

#包括
模板
结构固定字符串
{
char-buf[N+1]{};
constexpr FixedString(char const*s)
{
对于(无符号i=0;i!=N;++i)buf[i]=s[i];
}
constexpr运算符char const*()const{return buf;}
//不再是强制性的了
自动运算符(const FixedString&)const=default;
};
模板FixedString(charconst(&)[N])->FixedString;
模板
福班
{
公众:
auto hello()常量{return Name;}
};
int main()
{
富富,;
std::cout的基础是,它的大多数用例都是通过(也称为constexpr析构函数和瞬态分配)更好地实现的,即能够在constexpr上下文中使用
std::string
本身


当然,即使您可以在constexpr中使用
std::string
,这也不会使它可用作NTTP,但看起来我们不会很快将结构字符串类引入标准。我建议您现在使用自己的结构字符串类,准备好将其别名为适当的第三方类一个出现在流行的库中,或者如果出现这种情况,则成为标准库。

请注意,C++20 NTTP在标准化过程中发生了变化。强结构平等不再使用默认的
运算符,即使它在reddit post发布时使用过。(更准确地说,新术语是“结构类型”。)实现是否支持用户定义的NTTP?如果支持,哪些支持,以及支持的程度如何?我的观点是,您的实现看起来像是最先进的!非类型模板参数的模板id占位符,默认的三向比较运算符,它暗示了相等运算符、结构类型,并且不超过necessary!实现是否更简洁?是我自己的问题还是提供了一个新功能而不是一个标准容器来实现这一点很奇怪?@Moia structural NTTPs不仅仅用于使用字符串作为模板参数,它们是一种更通用的工具。如果这两个功能结合在一起,我们可能就没有这两个功能了。
#include <iostream>

template<unsigned N>
struct FixedString 
{
    char buf[N + 1]{};
    constexpr FixedString(char const* s) 
    {
        for (unsigned i = 0; i != N; ++i) buf[i] = s[i];
    }
    constexpr operator char const*() const { return buf; }

    // not mandatory anymore
    auto operator<=>(const FixedString&) const = default;
};
template<unsigned N> FixedString(char const (&)[N]) -> FixedString<N - 1>;

template<FixedString Name>
class Foo 
{
public:
    auto hello() const { return Name; }
};

int main() 
{
    Foo<"Hello!"> foo;
    std::cout << foo.hello() << std::endl;
}