使用模板功能专门化时的模块依赖性 [英] Module dependencies when using template function specializations

查看:77
本文介绍了使用模板功能专门化时的模块依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看以下代码段(伪代码,未编译):

Please check out the following code snippet (pseudo code, didn't compile it):

Ah

template <typename T>
void SubTest(T t) = delete;

template <>
void SubTest(int i)
{
    cout << i;
}

template <typename T>
class MyClass
{
    public:
        void Test(T t)
        {
            SubTest(t);
        }
}

Bh

class X{};

template <>
void SubTest(X x)
{
    cout << x;
}

您可以看到我想要一个类模板方法来调用函数模板。该功能以各种方式专门化。有些专业位于A.h中,有些则位于可选标头中(如B.h)。
我想避免A.h依赖于B.h等,因为A.h可以独立工作,但可以通过其他许多提供专业化的模块扩展。从逻辑上讲,这种依赖性不是必需的,但从技术上讲似乎是无法避免的。

As you can see I want a class template method to call a function template. That function is specialized in various ways. Some of the specializations are located in A.h, some in other in optional headers (like B.h). I want to avoid A.h to be dependent from B.h etc. since A.h can work standalone but should be extendable by an number of other other modules providing specializations. Logically this dependency is not necessary but it seems technically it can not be avoided.

AFAIK C ++需要两个条件:

AFAIK C++ requires two conditions:


  1. 使用所有规范之前必须先声明

  2. 必须在每次专门化之前声明主函数原型

我可以在Bh中包含Ah或者我可以重复 template< typename T> void SubTest(T t)= delete; 在Bh中满足条件2。但是,这仍然不能满足1。

I could include A.h in B.h. or I could repeat template <typename T> void SubTest(T t) = delete; in B.h to fulfill condition 2. However this still wouldn't fulfill 1.

我可以包括Bh在Ah中间,但是会(在逻辑上)造成不必要的依赖。

I could include B.h in the middle of A.h but that would create a (logically) unwanted dependency.

有没有一种方法可以在C ++到C ++的编译时解决此问题。 20?

Is there a way to solve this problem at compile time in C++ up to C++20?

推荐答案

确实,专业化需要在使用前声明,但这并不意味着在专业化之前呼叫者已被定义,但在实例化之前,可以使用所涉及的专业化。这对于任何定制方案都是至关重要的:先定义基本情况,然后定义客户端 #include 并在定义后立即为其类定义特殊化。如果其他客户拥有可用的类,则他们必然具有可用的专业知识,因此一切正常。自 C ++ 98 以来,这些都没有改变。

While it’s true that specializations "need to be declared before they are used", that doesn’t mean before their caller is defined, but before it is instantiated so as to use the specialization in question. This is critical to any customization scheme: you define the base case, then clients #include that and define specializations for their classes immediately after their definitions. Further clients necessarily have the specializations available if they have the classes available, so everything works. None of this has changed since C++98.

(同时,您不能重复 = delete 表示一个函数:该函数视为定义,并且也必须出现在第一个声明中。)

(Meanwhile, you can’t repeat =delete for a function: that counts as a definition, and must appear on the first declaration as well.)

这篇关于使用模板功能专门化时的模块依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆