简体   繁体   English

在Objective-C中使用模板调用C ++函数

[英]calling c++ function with template in objective-c

im trying to call a c++ template function in objective c that looks like this: 我试图在目标c中调用如下的c ++模板函数:

template<typename T>
void test() {
    ...

    std::cout << "hello world! \n";
}

Im getting the following error with calling test() : 我通过调用test()得到以下错误:

Undefined symbols for architecture armv7:
"test()", referenced from:
 -[viewController onNext] in ViewController.o
ld: symbol(s) not found for architecture armv7
clang: error: linker command failed with exit code 1 (use -v to see invocation)

if i take out template<typename T> it works fine, however, i need to use some functions from a c++ library that require templates and i cant get around it. 如果我取出template<typename T>它工作正常,但是,我需要使用c ++库中的一些需要模板的函数,而我却无法解决它。 any idea on whats happening? 有什么想法吗?

I have no experience with c++ what so ever... 我对c ++没有任何经验...

In C++, when you call a templated function, if the template parameter (ie T in your code) can't be deduced from the parameter passed to the function (which is your case since your function doesn't have any parameter), you shall call the function like this: 在C ++中,当您调用模板函数时,如果无法从传递给函数的参数中推导出模板参数(即代码中的T)(这是您的情况,因为您的函数没有任何参数),应该这样调用函数:

test< someType >(); 测试<someType>();

In C++: 在C ++中:

  • void test()
  • template<>void test<int>()
  • template<>void test<float>()

(as examples) are all different symbols. (例如)都是不同的符号。 by removing the template/parameter, it's a different symbol which matches the one you call in -[viewController onNext] . 通过删除模板/参数,它是一个与您在-[viewController onNext]调用的符号匹配的符号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM