Is it possible to typedef a pointer-to-extern-“C”-function type within a template?

旧城冷巷雨未停 提交于 2019-12-05 19:55:58

问题


I want to add a public typedef to a template for a pointer to a function-taking-one-argument that uses "C" language linkage.

I tried:

extern "C" {
    template <typename return_t_, typename arg1_t_>
    struct test
    {
        typedef return_t_ (*C_fun1_t)(arg1_t_);
    };
}

And:

template <typename return_t_, typename arg1_t_>
struct test
{
    extern "C" {
        typedef return_t_ (*C_fun1_t)(arg1_t_);
    }
};

And:

template <typename return_t_, typename arg1_t_>
struct test
{
    extern "C" typedef return_t_ (*C_fun1_t)(arg1_t_);
};

without success.

Is what I am trying to accomplish possible?


回答1:


C++03, §7.5p4:

A linkage-specification shall occur only in namespace scope. … A C language linkage is ignored for the names of class members and the member function type of class member functions.

Unfortunately, you simply can't do this in current C++. This text is unchanged in the latest C++0x draft, but "template typedefs" may be able to accomplish it.




回答2:


Consider typedef of a boost::function or the STL function objects ... also you can't define a template inside a extern "C" block for some quite obvious reasons if you think about it.




回答3:


Everything seems to work fine for me if I just omit the extern "C" from your typedef. That is, the following compiles, links, and runs without warnings, errors, or problems:

foo.c:

#include <stdio.h>
int foo(int x) {
    return printf("%x\n", x);
}

test.cpp:

extern "C" int foo(int);

template <typename return_t_, typename arg1_t_>
struct test
{
    typedef return_t_ (*C_fun1_t)(arg1_t_);
    C_fun1_t myFn;
};

int main() {
    test<int, int> t;
    t.myFn = foo;
    return t.myFn(5);
}

For the C++ gurus: I don't know the finer points of what distinguishes C linkage from C++. Are there any hidden problems that wouldn't turn up in a simple example like this?



来源:https://stackoverflow.com/questions/4866433/is-it-possible-to-typedef-a-pointer-to-extern-c-function-type-within-a-templat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!