将模板与类模板扣除占位符参数匹配

Match template with Class Template Deduction Placeholder param

本文关键字:参数 占位符      更新时间:2023-10-16

尝试在GCC 10.1中使用字符串文字作为非类型模板参数。具有以下代码:

#include <cstddef>
#include <algorithm>
#include <iostream>
template<std::size_t n> struct fixed_string {
constexpr fixed_string(char const (&s)[n]) {
std::copy_n(s, n, this->el);
}
constexpr fixed_string(fixed_string<n> const& s) {
std::copy_n(s.el, n, this->el);
}
constexpr bool operator==(fixed_string const&) const = default;
constexpr auto operator<=>(fixed_string const&) const = default;
char el[n];
};
template<std::size_t n> fixed_string(char const(&)[n])->fixed_string<n>;
template<fixed_string str>
class Base {
public:
Base() {
std::cout << str.el << std::endl;
}
};
template<fixed_string str>
class Derived : public Base<str> {
};

int main(void) {
Derived<"Hello World"> x;
}

Base本身工作得很好,它试图弄清楚如何将字符串文本传递到类层次结构中。我以为复制构造函数会起作用,GCC抛出了这个可爱的错误消息,并嘲笑我的尝试:

error: no matching function for call to ‘fixed_string(fixed_string<...auto...>)’
note: candidate: ‘template<long unsigned int n> fixed_string(const fixed_string<n>&)-> fixed_string<n>’
constexpr fixed_string(fixed_string<n> const& s) {
^~~~~~~~~~~~
note:   template argument deduction/substitution failed:
note:   mismatched types ‘const fixed_string<n>’ and ‘fixed_string<...auto...>’

酷。所以CCD_ 2是GCC;类模板扣除占位符";我不知道如何威胁编译器将其与我的函数调用相匹配。有人知道如何在这里胁迫GCC吗?或者,如何通过类层次结构传播字符串文字?

有趣的是,将str.el传递给Base模板会导致GCC崩溃。

这肯定是一个gcc错误。我经历过,并找到了这个解决方法:

template<std::size_t n> struct fixed_string {
consteval fixed_string(char const (&s)[n]) {
std::copy_n(s, n, this->el);
}
consteval fixed_string(const fixed_string<n>& s) = default;
consteval bool operator==(fixed_string const&) const = default;
consteval auto operator<=>(fixed_string const&) const = default;
char el[n];
static const std::size_t size = n;
};
template<std::size_t n> fixed_string(char const(&)[n])->fixed_string<n>;
template<std::size_t n, fixed_string<n> str>
class BaseImpl {
public:
BaseImpl() {
std::cout << str.el << std::endl;
}
};
template <fixed_string s>
using Base = BaseImpl<s.size, s>;
template<std::size_t n, fixed_string<n> str>
class DerivedImpl : public BaseImpl<n, str> {
};
template <fixed_string s>
using Derived = DerivedImpl<s.size, s>;
int main(void) {
Derived<"Hello World"> x;
}

或者

template<fixed_string str>
class Base {
public:
Base() {
std::cout << str.el << std::endl;
}
};
template <std::size_t n, fixed_string<n> s>
using BaseWrapper = Base<s>;
template<fixed_string str>
class Derived : public BaseWrapper<str.size, str> {
};

一般的想法是避免使用推导的参数来推导另一个参数。