如何将模板化固定字符串传递给另一个类的构造函数的重载

问题描述 投票:0回答:1

我在尝试传递已经初始化的字符串时遇到问题,该字符串实际上没有正确接受重载:

#include <cstddef>
#include <ranges>
#include <algorithm>
#include <iostream>

template <std::size_t N>

    class A {
        char m_m[N];
        public:
            A(char const (&p)[N]) {
                // Copy p to m_m
                std::ranges::copy(p, m_m);
            }
    };

template <std::size_t N>
    class B {
        public: B(A<N> a) {
            // Perform some operation on 'a'
        }
    };

int main() {
    auto k = B("test");
}

采取,过载正确,但我目前得到:

prog.cc:26:22: error: no matching function for call to 'B(const char [5])'
prog.cc:20:5: note: candidate: 'template<long unsigned int N> B(A<N>)-> B<N>'
20 |     B(A<N> a) {
c++ templates c++20 variadic-templates template-meta-programming
1个回答
0
投票

代码中的问题是类

B
的构造函数需要一个
A<N>
类型的对象,但您试图传递一个字符串文字,它是一个字符数组,而不是
A<N>
类型的对象。

您可以修改

B
构造函数以直接接受字符串文字。

这是代码的更新版本:

#include <cstddef>
#include <ranges>
#include <algorithm>
#include <iostream>

template <std::size_t N>
class A {
    char m_m[N];

public:
    A(char const (&p)[N]) {
        // Copy p to m_m
        std::copy(p, p + N, m_m);
    }
};

template <std::size_t N>
class B {
public:
    B(const char (&p)[N]) {
        A<N> a(p);
        // Perform some operation on 'a'
    }
};

int main() {
    auto k = B("test");
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.