0

我以前曾以多种方式看到过这个问题,所有解决方案总是相同的:使用辅助函数,甚至使用嵌套类。对我来说,这两种解决方案看起来都很笨拙。所以我想知道为什么在c++17/c++20时代没有更好的解决这个问题的办法:

编辑:这里的问题是是否有任何方法可以使用impl<int> i(b);,因为当前编译器由于缺少第二个模板参数而失败。

template<class T1, class T2>
struct impl
{
    impl(const T2& _t2) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl<int> i(b);//... but this doesn't due to lack of 2nd template parameter!!!
}

我了解部分专业化在某些情况下会出现问题,但在这种情况下无法使用 CTAD 或任何其他方法???如果是这样,怎么做?

4

1 回答 1

2

我最常使用“类型标签”来克服这类问题。对于类似的问题,它也很方便,比如缺少函数模板的部分专业化。

#include <type_traits>

template<typename T> struct type_t{};
template<typename T> constexpr type_t<T> type;

template<class T1, class T2>
struct impl
{
    impl(const T2& _t2, type_t<T1> = {}) : t2(_t2) {}

    T1 t1;
    const T2& t2;
};

int main()
{
    int a{};
    double b{};
    impl<int, double> i(b);//This works...
    impl j(b, type<int>); // This works as well
    static_assert(std::is_same_v<decltype(j),impl<int, double>>);
}
于 2022-02-09T18:47:37.287 回答