swift uses c++20/23 concepts - Posted on Jun 18, 2024 - See https://www.swift.org/documentation/cxx-interop - Logs Home - d0024
Download and install swift latest snapshot (6.0).
Install clang libc++
apt install libc++-dev libc++abi-dev
Create swift c++ project.
Commands :
mkdir -p hello_swift/{Sources/hello_cpp/include,Sources/hello_swift} cd hello_swift/ kak Package.swift
Package.swift :
// swift-tools-version: 6.0 import PackageDescription let package = Package( name: "hello_swift", targets: [ .target( name: "hello_cpp" ), .executableTarget( name: "hello_swift", dependencies: ["hello_cpp"], swiftSettings: [.interoperabilityMode(.Cxx)] ) ] )
Commands :
cd Sources/hello_cpp/include/ kak any_name.cpp
c++ code :
any_name.cpp
#pragma once #include <iostream> #include <concepts> namespace any { template <typename type_xtk> concept number = std::integral<type_xtk> || std::floating_point<type_xtk>; template <any::number type_xti> class test { public: void print() const { constexpr auto value__ = static_cast<type_xti>(234.432); std::cout << "value__ : " << value__ << std::endl; } }; class hello_cpp_any_name { public: void print() const { any::test<int>{}.print(); any::test<float>{}.print(); } }; } // namespace any
Commands :
cd - # cd <project root dir> cd Sources/hello_swift/ kak any_name.swift
swift code :
any_name.swift
import hello_cpp class hello_swift { public func print() { let object = any.hello_cpp_any_name() object.print() } } var hello = hello_swift() hello.print() var ob1 = any.hello_cpp_any_name() ob1.print() let ob2 = any.hello_cpp_any_name() ob2.print()
c++ compiler and linker flags must be passed to both "swift build" and "swift run" .
gcc libstdc++ latest c++20/23 can not work for swift compiler in the moment.
libc++ c++20/23 can work with swift compiler in the moment.
swift run -Xcc -std=c++23 -Xcc -stdlib=libc++ -Xlinker -lc++
$ swift run -Xcc -std=c++23 -Xcc -stdlib=libc++ -Xlinker -lc++ Building for debugging... [1/1] Write swift-version-32A5E7755150B194.txt Build of product 'hello_swift' complete! (0.01s) value__ : 234 value__ : 234.432 value__ : 234 value__ : 234.432 value__ : 234 value__ : 234.432
c++ std::exception:
std::cout.write(err.data(), err.size());
std::cout << std::endl;
caught:
=================================== # The c++ programming language. # # # # Join c++ Discord: yZcauUAUyC # # Deck # ===================================