使用包含字符串的模板对象创建可变参数模板

stg*_*pns 1 c++ templates variadic-templates c++20

我想创建一个模板,它将采用包含字符串的特定类的变量号。当我尝试创建这样的模板类时,它抛出 没有与参数列表匹配的构造函数“A”的实例

A类:

template<template_string s>
class A {};
Run Code Online (Sandbox Code Playgroud)

B类:

template<A... As>
class B {};
Run Code Online (Sandbox Code Playgroud)

模板_字符串.h:

template<size_t _N>
struct template_string {
char c_str[_N];

    constexpr template_string(const char(&text)[_N]) {
        std::copy(text, text+_N, c_str);
    }

    constexpr std::string std_str() const noexcept {
        return std::string(c_str);
    }
    constexpr std::string_view str_view() const noexcept {
        return std::string_view(c_str);
    }

    constexpr size_t length() const noexcept {
        return _N-1;
    }

};
Run Code Online (Sandbox Code Playgroud)

我想通过模板和类明确地做到这一点。我需要做什么才能构建 B 类:

B<A<"text">(), A<"other text">(),....> b;
Run Code Online (Sandbox Code Playgroud)

use*_*445 5

这是“最令人烦恼的解析”问题的一个实例,看起来您正在声明一个函数类型而不是在对象上创建。这是一个完整的工作示例,其中我()用统一的初始化语法替换了函数调用{}

#include <cstddef>
#include <string>

using std::size_t;

template<size_t _N> requires (_N >= 1)
struct template_string {
    char c_str[_N];

    constexpr template_string(const char(&text)[_N]) {
        std::copy(text, text+_N, c_str);
    }

    constexpr std::string std_str() const noexcept {
        return std::string(c_str);
    }
    constexpr std::string_view str_view() const noexcept {
        return std::string_view(c_str, length());
    }

    constexpr size_t length() const noexcept {
        return _N-1;
    }

};


template<template_string s>
class A {};

template<A... As>
class B {};

int
main()
{
    [[maybe_unused]] B<A<"text">{}, A<"other text">{}> b;
}
Run Code Online (Sandbox Code Playgroud)

我做的另一件事是string_view使用字符串的长度创建 ,以防万一字符串包含 NUL 字节,如"hello\0there".